package cn.chiship.framework.third.biz.wxpub.controller;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.all.service.ThirdCacheService;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.framework.third.core.common.WechatUtils;
import cn.chiship.sdk.core.util.OutUtil;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;

import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatQrcodeService;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatQrcode;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatQrcodeExample;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.ThirdWechatQrcodeDto;
import cn.chiship.sdk.third.wx.core.config.WeiXinConfig;
import cn.chiship.sdk.third.wx.network.WxPubServicesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 二维码控制层
 * 2022/7/14
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/thirdWechatQrcode")
@Api(tags = "二维码")
public class ThirdWechatQrcodeController extends BaseController<ThirdWechatQrcode, ThirdWechatQrcodeExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatQrcodeController.class);

    @Resource
    private ThirdWechatQrcodeService thirdWechatQrcodeService;

    @Resource
    private ThirdCacheService cacheService;

    @Override
    public BaseService getService() {
        return thirdWechatQrcodeService;
    }

    @SystemOptionAnnotation(describe = "二维码分页")
    @ApiOperation(value = "二维码分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),

    })
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(@RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        ThirdWechatQrcodeExample thirdWechatQrcodeExample = new ThirdWechatQrcodeExample();
        /**
         * 创造条件
         */
        ThirdWechatQrcodeExample.Criteria thirdWechatQrcodeCriteria = thirdWechatQrcodeExample.createCriteria();
        thirdWechatQrcodeCriteria.andIsDeletedEqualTo(BaseConstants.NO).andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            thirdWechatQrcodeCriteria.andTitleLike(keyword + "%");
        }
        return super.responseEntity(BaseResult.ok(super.page(thirdWechatQrcodeExample)));
    }

    @SystemOptionAnnotation(describe = "二维码列表数据")
    @ApiOperation(value = "二维码列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(@RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        ThirdWechatQrcodeExample thirdWechatQrcodeExample = new ThirdWechatQrcodeExample();
        /**
         * 创造条件
         */
        ThirdWechatQrcodeExample.Criteria thirdWechatQrcodeCriteria = thirdWechatQrcodeExample.createCriteria();
        thirdWechatQrcodeCriteria.andIsDeletedEqualTo(BaseConstants.NO).andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            thirdWechatQrcodeCriteria.andTitleLike(keyword + "%");
        }
        return super.responseEntity(BaseResult.ok(super.list(thirdWechatQrcodeExample)));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存二维码")
    @ApiOperation(value = "保存二维码")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid ThirdWechatQrcodeDto thirdWechatQrcodeDto) {
        ThirdWechatQrcode thirdWechatQrcode = new ThirdWechatQrcode();
        BeanUtils.copyProperties(thirdWechatQrcodeDto, thirdWechatQrcode);
        return super.responseEntity(super.save(thirdWechatQrcode));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新二维码")
    @ApiOperation(value = "更新二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path", required = true)
    })
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid ThirdWechatQrcodeDto thirdWechatQrcodeDto) {
        ThirdWechatQrcode thirdWechatQrcode = new ThirdWechatQrcode();
        BeanUtils.copyProperties(thirdWechatQrcodeDto, thirdWechatQrcode);
        return super.responseEntity(super.update(id, thirdWechatQrcode));
    }

    @SystemOptionAnnotation(describe = "场景码生成", option = BusinessTypeEnum.SYSTEM_OPTION_OTHER)
    @ApiOperation(value = "场景码生成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path", required = true),
    })
    @GetMapping("generateQrCode/{id}")
    public void generateQrCode(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ThirdWechatQrcode thirdWechatQrcode = thirdWechatQrcodeService.selectByPrimaryKey(id);
        ThirdApplicationKeyConfig applicationKeyConfig = cacheService.getConfigByAppId();
        WeiXinConfig weiXinConfig = new WeiXinConfig(applicationKeyConfig.getAppId(), applicationKeyConfig.getAppSecret());
        WxPubServicesUtil weiXinPubServicesUtil = WxPubServicesUtil.getInstance().config(weiXinConfig).token();
        BaseResult baseResult = null;
        if (BaseConstants.NO == (thirdWechatQrcode.getType())) {
            /**
             * 临时二维码
             */
            baseResult = weiXinPubServicesUtil.getQrCodeByTemporary(thirdWechatQrcode.getExpireSeconds(), id);
        }
        if (BaseConstants.YES == (thirdWechatQrcode.getType())) {
            /**
             * 永久二维码
             */
            baseResult = weiXinPubServicesUtil.getQrCodeByForever(id);
        }
        if (!baseResult.isSuccess()) {
            OutUtil.writeJson(response, BaseResult.error(baseResult.getData()));
            return;
        }
        byte[] bytes = (byte[]) baseResult.getData();
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");


        ServletOutputStream out = response.getOutputStream();
        IOUtils.write(bytes, out);
        out.flush();
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除二维码")
    @ApiOperation(value = "删除二维码")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        ThirdWechatQrcodeExample thirdWechatQrcodeExample = new ThirdWechatQrcodeExample();
        thirdWechatQrcodeExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(thirdWechatQrcodeExample));
    }
}